package com.renwei.yunlong.activity.work;

import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.DetailsBean;
import com.renwei.yunlong.bean.ReturnBean;
import com.renwei.yunlong.event.SparePageRefreshEvent;
import com.renwei.yunlong.event.SparePageStateRefreshEvent;
import com.renwei.yunlong.fragment.BaseAnnexFragment;
import com.renwei.yunlong.fragment.BaseHistoryFragment;
import com.renwei.yunlong.fragment.SpareDetailsFragment;
import com.renwei.yunlong.fragment.WorkDetailsFragment;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;

/**
 * 备件申请相关 -- 页面
 * <p>
 * Created by Administrator on 2017/8/30.
 */

public class SpareInformationActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, PromptButtonListener {

    @Bind(R.id.tab_layout)
    TabLayout mTabLayout;
    @Bind(R.id.v_pager)
    ViewPager mViewPager;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.btn_next)
    Button btnNext;
    @Bind(R.id.rl_button)
    RelativeLayout rlButton;

    private TablayoutAdapter adapter;
    private static final String POWER_QUERENSHOUHUO = "确认收货";
    private static final String POWER_SHENHE = "审核";
    private HashSet<String> powerSet;
    private DetailsBean detailsBean;
    private PromptDialog promptDialog;
    private String requestId;
    private String sprId;
    private String outsourceFlag;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spare_application);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);
        requestId = getIntent().getStringExtra("requestId");
        sprId = getIntent().getStringExtra("sprId");
        outsourceFlag = getIntent().getStringExtra("outsourceFlag");
        initView();
        initData();

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(SparePageRefreshEvent event) {
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvTitle.setText("备件申请相关");
        btnNext.setOnClickListener(this);
        //页面，数据源
        ArrayList<Fragment> list = new ArrayList<>();
        list.add(new BaseHistoryFragment(sprId, "spare", outsourceFlag));
        list.add(new SpareDetailsFragment(sprId));
        list.add(new BaseAnnexFragment(sprId, "spare"));
        list.add(new WorkDetailsFragment(requestId, outsourceFlag, false));
        String[] titles = {"申请过程", "申请信息", "相关附件", "工单详情"};
        //ViewPager的适配器
        adapter = new TablayoutAdapter(getSupportFragmentManager(), list, titles);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(3);
        // 弹框
        promptDialog = new PromptDialog(this);
        //绑定
        mTabLayout.setupWithViewPager(mViewPager);
    }

    private void initData() {
        ServiceRequestManager.getManager().getSpareDetail(this, sprId, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.btn_next:
                setDialog();
                break;
            default:
                break;
        }
    }

    private void setDialog() {

        if (powerSet.size() != 0) {
            PromptButton[] buttons = new PromptButton[powerSet.size() + 1];
            buttons[0] = new PromptButton("取消", null);
            int i = 0;
            for (String s : powerSet) {
                i++;
                buttons[i] = new PromptButton(s, this);
            }
            promptDialog.showBottomAlert("", true, buttons);
        }
    }

    @Override
    public void onClick(PromptButton button) {
        switch (button.getText()) {
            case POWER_QUERENSHOUHUO:
                showDialog();
                break;
            case POWER_SHENHE:
                Intent intent = new Intent(SpareInformationActivity.this, SpareAuditActivity.class);
                intent.putExtra("sprId", sprId);
                intent.putExtra("spareId", detailsBean.getRows().getSpareId());
                intent.putExtra("sprName", detailsBean.getRows().getSprHardName());
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    //显示dialog
    private void showDialog() {

        DialogUtils.showDialog(this, "您确认收到货物了吗？", true, new DialogUtils.OnDialogClickListener() {
            @Override
            public void onCancel(Dialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onConfirm(Dialog dialog) {
                HashMap<String, String> map = new HashMap<>();
                if ("1".equals(companyType)) {
                    map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                } else if ("2".equals(companyType)) {
                    map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                }
                map.put("receivState", "1");
                map.put("sprId", sprId);
                ServiceRequestManager.getManager().setSpareGoods(mContext, JsonMapUtil.mapToJson(map), SpareInformationActivity.this);
                dialog.dismiss();
            }
        });

    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                powerSet = new HashSet();
                detailsBean = new Gson().fromJson(result, DetailsBean.class);
                if (detailsBean.getMessage().getCode() == 200) {
                    if ("1".equals(companyType)) {
                        if (!"1".equals(detailsBean.getRows().getReceivState())) {
                            if ("1".equals(detailsBean.getRows().getFlag()) &&
                                    ("4".equals(ownerBean.getRows().getEmployee().getRoleId()) || "12".equals(ownerBean.getRows().getEmployee().getRoleId()))) {
                                //审核
                                powerSet.add(POWER_SHENHE);
                            } else if ("2".equals(detailsBean.getRows().getFlag())) {
                                if (detailsBean.getRows().getApplyerId().equals(ownerBean.getRows().getEmployeeId())) {
                                    //确认收货
                                    powerSet.add(POWER_QUERENSHOUHUO);
                                }
                            }
                        }
                    } else {
                        if (!"1".equals(detailsBean.getRows().getReceivState())) {
                            if ("1".equals(detailsBean.getRows().getFlag()) &&
                                    ("4".equals(serviceLoginBean.getRows().getEmployee().getRoleId()) || "12".equals(serviceLoginBean.getRows().getEmployee().getRoleId()))) {
                                //审核
                                powerSet.add(POWER_SHENHE);
                            } else if ("2".equals(detailsBean.getRows().getFlag())) {
                                if (detailsBean.getRows().getApplyerId().equals(serviceLoginBean.getRows().getEmployeeId())) {
                                    //确认收货
                                    powerSet.add(POWER_QUERENSHOUHUO);
                                }
                            }
                        }
                    }
                    if (powerSet.size() == 0) {
                        EventBus.getDefault().post(new SparePageStateRefreshEvent(detailsBean.getRows().getFlag(), false));
                        rlButton.setVisibility(View.GONE);
                    } else {
                        EventBus.getDefault().post(new SparePageStateRefreshEvent(detailsBean.getRows().getFlag(), true));
                        rlButton.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 2://业主确认收货
                ReturnBean ownerGoods = new Gson().fromJson(result, ReturnBean.class);
                if (ownerGoods.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("操作成功");
                    EventBus.getDefault().post(new SparePageRefreshEvent());
                } else if (ownerGoods.getMessage().getCode() == 1008) {
                    showCenterInfoMsg("无权限访问");
                } else {
                    showCenterInfoMsg(ownerGoods.getMessage().getMessage());
                }
                break;
                default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, String requestId, String outsourceFlag, String sprId) {
        Intent intent = new Intent(context, SpareInformationActivity.class);
        if (context instanceof Application) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra("requestId", requestId);
        intent.putExtra("outsourceFlag", outsourceFlag);
        intent.putExtra("sprId", sprId);
        context.startActivity(intent);
    }
}
